<template>
  <el-card class="content-section hospital-comparison">
    <div class="section-header">
      <div style="display: flex;align-items: center;">
        <h2 class="section-title">各医院标签使用对比</h2>
        <div class="section-info" style="margin-left: 70px;">
          <div class="filter-controls">
            <el-select v-model="activationFilter" placeholder="选择医院状态" style="width: 150px">
              <el-option v-for="option in activationFilterOptions" :key="option.value" :label="option.label"
                :value="option.value">
              </el-option>
            </el-select>
          </div>
        </div>
      </div>
      <div class="update-info">
        <el-button type="primary" icon="el-icon-download" size="mini" @click="exportData">导出数据</el-button>
        <span class="update-frequency" @click="refreshData">每日更新</span>
        <span class="last-updated">更新于: {{ updateTime }}</span>
      </div>
    </div>

    <!-- 全局对比与标杆分析表格 -->
    <div class="table-scroll-wrapper">
      <el-table :data="hospitalComparisonData" style="width: 100%; min-width: 1500px; table-layout: fixed;" stripe
        @sort-change="handleSortChange">
        <el-table-column prop="corpName" label="医院名称" width="200">
          <template slot-scope="scope">
            <span
              :class="{ 'hospital-name': true, 'benchmark': scope.row.isBenchmark, 'problem': scope.row.isProblem }">
              {{ scope.row.corpName }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="hospitalParentTagCount" label="医院标签组数量" sortable="custom" width="190">
          <template slot="header">
            <span>医院标签组数量</span>
            <el-tooltip content="该医院下由医院统一创建的标签组数量" placement="top">
              <i class="el-icon-question tooltip-icon"></i>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="hospitalChildTagCount" label="医院标签总数" sortable="custom" width="180">
          <template slot="header">
            <span>医院标签总数</span>
            <el-tooltip content="该医院的医院标签总数量" placement="top">
              <i class="el-icon-question tooltip-icon"></i>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="hospitalPatientCount" label="医院标签下患者数" sortable="custom" width="210">
          <template slot="header">
            <span>医院标签下患者数</span>
            <el-tooltip content="该医院的医院标签下累计覆盖的患者（去重）总数" placement="top">
              <i class="el-icon-question tooltip-icon"></i>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="personalParentTagCount" label="个人标签组数量" sortable="custom" width="190">
          <template slot="header">
            <span>个人标签组数量</span>
            <el-tooltip content="该医院的所有医护创建个人标签组数量" placement="top">
              <i class="el-icon-question tooltip-icon"></i>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="personalChildTagCount" label="个人标签总数" sortable="custom" width="170">
          <template slot="header">
            <span>个人标签总数</span>
            <el-tooltip content="该医院的所有医护创建的个人标签的总数量" placement="top">
              <i class="el-icon-question tooltip-icon"></i>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="personalPatientCount" label="个人标签下患者数" sortable="custom" width="210">
          <template slot="header">
            <span>个人标签下患者数</span>
            <el-tooltip content="该医院的个人标签下累计覆盖的患者（去重）总数" placement="top">
              <i class="el-icon-question tooltip-icon"></i>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="penetrationRate" label="标签医护渗透率" sortable="custom" width="210">
          <template slot="header">
            <span>标签医护渗透率</span>
            <el-tooltip content="该医院内至少有过一次标签使用事件（给患者打标签、患者主动关怀选标签、随访选标签）的去重激活医护数/该医院激活医护总数，反映了标签功能在医院的普及程度"
              placement="top">
              <i class="el-icon-question tooltip-icon"></i>
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <span
              :class="{ 'metric-value': true, 'good': scope.row.penetrationRate >= 80, 'medium': scope.row.penetrationRate >= 50 && scope.row.penetrationRate < 80, 'bad': scope.row.penetrationRate < 50 }">
              {{ scope.row.penetrationRate }}%
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="perCapita" label="人均个人标签数" sortable="custom" width="190">
          <template slot="header">
            <span>人均个人标签数</span>
            <el-tooltip content="该医院激活医护创建的不重复的个人标签的总数 / 该医院至少创建过一个个人标签的不重复激活医护总数，数值越高说明医院预设的标准化标签越不能满足员工的个性化工作需求"
              placement="top">
              <i class="el-icon-question tooltip-icon"></i>
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <span
              :class="{ 'metric-value': true, 'good': scope.row.perCapita >= 10, 'medium': scope.row.perCapita >= 5 && scope.row.perCapita < 10, 'bad': scope.row.perCapita < 5 }">
              {{ scope.row.perCapita }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="tagUsageRatio" label="医院标签使用占比"  sortable="custom" width="210">
          <template slot="header">
            <span>医院标签使用占比</span>
            <el-tooltip
              content="该医院官方制定的'医院标签'使用次数/该医院的医护自行创建的'个人标签'使用次数，医院标签使用次数占比高说明医院标准化标签定义的好，医生更愿意遵循官方流程。个人标签使用次数占比高说明医生更愿意使用自己创建的标签，官方标签严重脱离一线实际。"
              placement="top">
              <i class="el-icon-question tooltip-icon"></i>
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <span
              :class="{ 'metric-value': true, 'good': scope.row.tagUsageRatio >= 70, 'medium': scope.row.tagUsageRatio >= 50 && scope.row.tagUsageRatio < 70, 'bad': scope.row.tagUsageRatio < 50 }">
              {{ scope.row.tagUsageRatio }}%
            </span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页控件 -->
    <div class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="pagination.currentPage" :page-sizes="[5, 10, 20, 50]" :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="pagination.total">
      </el-pagination>
    </div>
  </el-card>
</template>

<script>
import { getEachHospitalTagUsage } from '@/api/chenlong.js'
import { download } from '@/utils/request'
export default {
  name: 'HospitalComparison',  //各医院标签使用对比
  data() {
    return {
      activationFilter: 'active',
      activationFilterOptions: [
        { label: '所有医院', value: 'all' },
        { label: '激活医院', value: 'active' },
        { label: '未激活医院', value: 'inactive' }
      ],
      // 分页信息
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      hospitalComparisonData: [],
      updateTime: '--',
      sorting: '',  //排序字段
      sortType: ''  //sortType排序方式 desc asc
    }
  },
  watch: {
    activationFilter: {
      handler(newVal, oldVal) {
        if (newVal !== oldVal) {
          // 筛选条件改变时，清除表头排序，使用筛选排序
          this.sorting = ''
          this.sortType = ''
          this.getData()
        }
      }
    }
  },
  computed: {
    currentFilterLabel() {
      const selectedOption = this.activationFilterOptions.find(option => option.value === this.activationFilter)
      return selectedOption ? selectedOption.label : ''
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    async getData(refresh = false) {
      const params = {
        pageSize: this.pagination.pageSize,
        pageNum: this.pagination.currentPage
      }
      if (refresh) {
        params.refresh = 'refresh'
      }
      // 优先使用表头排序，如果没有则使用筛选排序
      if (this.sorting && this.sortType) {
        params.sorting = this.sorting
        params.sortType = this.sortType
      } else {
        // 使用筛选排序作为默认排序，默认为激活医院
        // params.sorting = this.currentFilterLabel || '激活医院'
        // params.sortType = 'activate'
        if (this.currentFilterLabel === '激活医院') {
          params.activate = 'activate'
        } else if (this.currentFilterLabel === '未激活医院') {
          params.activate = 'noActivate'
        } else if (this.currentFilterLabel === '所有医院') {
          params.activate = ''
        }

        //激活医院 activate 未激活医院 noActivate 所有医院 ''

      }
      const res = await getEachHospitalTagUsage(params)
      if (res.code == 200) {
        this.hospitalComparisonData = res.data.list
        this.pagination.total = res.data.total
        this.updateTime = res.data.updateTime || this.formatCurrentTime()
      }
    },
    async refreshData() {
      try {
        await this.getData(true)
        this.$message.success('数据更新成功')
      } catch (error) {
        this.$message.error('数据更新失败，请重试')
      }
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.pagination.currentPage = 1
      this.getData()
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.getData()
    },
    formatCurrentTime() {
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      const day = String(now.getDate()).padStart(2, '0')
      const hours = String(now.getHours()).padStart(2, '0')
      const minutes = String(now.getMinutes()).padStart(2, '0')
      return `${year}.${month}.${day} ${hours}:${minutes}`
    },
    // 表格排序变化处理
    async handleSortChange({ column, prop, order }) {
      if (order === null) {
        // 取消排序，恢复默认排序
        this.sorting = ''
        this.sortType = ''
      } else {
        // 设置排序字段和排序方式
        this.sorting = prop
        this.sortType = order === 'ascending' ? 'asc' : 'desc'
      }

      // 重置到第一页
      this.pagination.currentPage = 1

      // 重新获取数据
      try {
        await this.getData()
        this.$message.success('排序成功')
      } catch (error) {
        this.$message.error('排序失败，请重试')
      }
    },
    // 导出数据
    exportData() {
      // 生成文件名：各医院标签使用对比_20250925
      const today = new Date()
      const year = today.getFullYear()
      const month = String(today.getMonth() + 1).padStart(2, '0')
      const day = String(today.getDate()).padStart(2, '0')
      const fileName = `各医院标签使用对比_${year}${month}${day}.xlsx`

      // 构建导出参数
      const params = {
        sorting: this.sorting || this.currentFilterLabel || '激活医院',
        sortType: this.sortType || 'desc'
        // pageSize: this.pagination.pageSize,
        // pageNum: this.pagination.currentPage
      }

      // 使用框架自带的下载方法，请求地址暂时为空
      this.download('/business/data/statistics/exportEachHospitalTagUsage', params, fileName)
    }
  }
}
</script>

<style lang="scss" scoped>
.content-section {
  background: #ffffff;
  border-radius: 8px;
  padding: 20px 20px 0 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  margin-bottom: 24px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #dddddd;
}

.section-title {
  font-size: 23px;
  font-weight: 600;
  margin: 0;
  border-left: 4px solid #4a90e2;
  padding-left: 12px;
}

.update-info {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #888888;
  font-size: 12px;
}

.update-frequency {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 2px 8px;
  background: rgba(74, 144, 226, 0.1);
  border-radius: 4px;
  white-space: nowrap;
  font-size: 16px;
  line-height: 1;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;

  &:hover {
    background-color: #409eff;
    color: #ffffff;
    transform: scale(1.05);
  }
}

.update-frequency::before {
  content: "⟳";
  font-size: 17px;
}

.last-updated {
  font-size: 15px;
  white-space: nowrap;
}

.el-button+.el-button {
  margin-left: 0;
}

.tooltip-icon {
  color: #4a90e2;
  cursor: help;
  margin-left: 4px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
  margin-bottom: 30px;

  /* ====== 加大 el-pagination 分页组件内所有文字的字号 ====== */
  ::v-deep .el-pagination {
    font-size: 16px;
  }

  /* 页码按钮（比如 1 2 3 4 5 ...） */
  ::v-deep .el-pagination .el-pager li {
    font-size: 16px !important;
    min-width: 32px;
    height: 32px;
    line-height: 32px;
  }

  /* 上一页 / 下一页 按钮 */
  ::v-deep .el-pagination .btn-prev,
  ::v-deep .el-pagination .btn-next {
    font-size: 16px !important;
    min-width: 32px;
    height: 32px;
    line-height: 32px;
  }

  /* 总条数（比如：共 100 条） */
  ::v-deep .el-pagination .el-pagination__total {
    font-size: 16px !important;
    line-height: 2.2;
  }

  /* 每页条数选择器（sizes）的文本和按钮 */
  ::v-deep .el-pagination .el-pagination__sizes {
    font-size: 16px !important;
  }

  ::v-deep .el-pagination .el-pagination__sizes .el-input .el-input__inner {
    font-size: 16px !important;
    height: 32px;
  }

  /* 跳转至输入框（比如：跳至 1 页） */
  ::v-deep .el-pagination .el-pagination__jump {
    font-size: 16px !important;
    line-height: 2.2;
  }

  ::v-deep .el-pagination .el-pagination__jump .el-input .el-input__inner {
    font-size: 16px !important;
    height: 32px;
  }

  /* 当前选中页码样式（可选美化） */
  ::v-deep .el-pagination .el-pager li.active {
    font-size: 16px !important;
    font-weight: 600;
    color: #409eff;
  }
}

/* ======================== 新增：表格内字体加大 3px ======================== */
/* 表头 th 字体 */
::v-deep .el-table .el-table__header th {
  font-size: 17px !important;
  font-weight: 600;
  color: #303133;
}

/* 表格单元格 td 字体 */
::v-deep .el-table .el-table__body td {
  font-size: 17px !important;
  color: #606266;
}

.table-scroll-wrapper {
  width: 100%;
  overflow-x: auto;
  min-width: 1500px;
  flex-shrink: 0;

  .el-table {
    min-width: 1200px !important;
    table-layout: fixed !important;

    ::v-deep .el-table__header-wrapper,
    ::v-deep .el-table__body-wrapper {
      min-width: 1200px !important;
    }

    ::v-deep .el-table__header th,
    ::v-deep .el-table__body td {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }

  /* 可选美化滚动条 */
  &::-webkit-scrollbar {
    height: 8px;
  }

  &::-webkit-scrollbar-track {
    background: #f1f1f1;
  }

  &::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 4px;
  }
}
</style>
